package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import vo.Area;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "PostalCodeServlet", value = "/postalCode")
public class Demo11_PostalCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //初始化邮编对应省市的一个Map key是邮编，value是省和市
        Map<String,String> postalCodeMap = new HashMap<>();

        postalCodeMap.put("157000","黑龙江,哈尔滨");
        postalCodeMap.put("148000","辽宁省,沈阳市");
        postalCodeMap.put("139000","吉林省,长春市");

        //初始化一个返回的省市字符串
//        String backData = "";
        
        //初始化一个Area的对象(实体类对象，用于把属性转json)
        Area area = new Area();

        //从前端页面获取填入的邮政编码
        String postalCode = request.getParameter("postalCode");

        if(postalCodeMap.containsKey(postalCode)){
            String value = postalCodeMap.get(postalCode);
            String[] provincesAndCity = value.split(",");
            
            area.setProvince(provincesAndCity[0]);
            area.setCity(provincesAndCity[1]);
            
            
//            backData = "{\"province\":\""+provincesAndCity[0]+"\",\"city\":\""+provincesAndCity[1]+"\"}";
        }else{
            
            area.setProvince("未知");
            area.setCity("未知");
            
            
//            backData = "{\"province\":\"未知\",\"city\":\"未知\"}";

        }

        //创建一个把实体类转成json格式的对象
        ObjectMapper mapper = new ObjectMapper();
        String backData = mapper.writeValueAsString(area);

        //如果是转发和重定向必然会重新加载整个页面
        //所以此处想要局部刷新，一定以此方式返回内容
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(backData);
        writer.close();

    }
}
